import React, { useEffect, useState,useCallback } from 'react';
import { Layout, Spin, Table, Modal, message } from 'antd';
import { getCrmRecordById, getCrmRecordFromSql, getFileContentAsString } from "../../util/util";

const { Sider, Content } = Layout;




const fieldsToCompare = [
  { label: '工厂代码', key: 'Plant.name' },
  { label: '工厂名称', key: 'PlantName' },
  { label: '外销合同号', key: 'Exportcontractnumber' },
  { label: '合同日期', key: 'Contract_Date' },
  { label: '出口国家', key: 'States.name' },
  { label: '合同类型', key: 'ContractType' },
  { label: '货好时间', key: 'Deliverytime' },
  { label: '装运港', key: 'ShippingPort.name' },
  { label: '目的港', key: 'DestinationPort.name' },
  { label: '货币', key: 'Currency' },
  { label: '生产要求', key: 'ProcurementTerms' }
];


// 子表字段比对配置
const childFieldsToCompare = [
  { label: '商品编码', key: 'Product.name' },
  { label: '客户订单号', key: 'AccountOrderNo' },
  { label: '数量', key: 'PurchaseQty' },
  { label: '每箱数量', key: 'Packagingquantityperpg' },
  { label: '包装单位', key: 'Packaginunit' },
  // { label: '数量', key: 'Quantity' },
];
// 比较两个JSON对象，并返回差异
const compareJson = (json1, json2, fieldsToCompare) => {
  const changes = [];

  fieldsToCompare.forEach(({ label, key }, index) => {
    // 处理点分隔的字段路径
    const keys = key.split('.');
    let value1 = json1;
    let value2 = json2;

    // 获取值
    keys.forEach((key) => {
      if (value1) value1 = value1[key];
      if (value2) value2 = value2[key];
    });

    // 比较值
    if (JSON.stringify(value1) !== JSON.stringify(value2)) {
      changes.push({
        key: index, // 添加唯一的 key
        field: label, // 使用用户友好的字段名
        originalValue: value1,
        newValue: value2,
      });
    }
  });

  return changes;
};

const compareChildTables = (json1, json2, fieldsToCompare) => {
  const changes = {
    added: [],
    modified: [],
    deleted: []
  };

  const json1Map = new Map((json1 || []).map(item => [item.id, item]));
  const json2Map = new Map((json2 || []).map(item => [item.id, item]));

  // Find added and modified items
  for (const [id, item2] of json2Map.entries()) {
    const item1 = json1Map.get(id);

    if (!item1) {
      // Item is added
      changes.added.push(item2);
    } else {
      // Item exists in both json1 and json2, check for modifications
      const modifiedFields = {};
      let isModified = false;

      for (const field of fieldsToCompare) {
        const oldValue = item1[field.key];
        const newValue = item2[field.key];

        if (JSON.stringify(oldValue) !== JSON.stringify(newValue)) {
          isModified = true;
          modifiedFields[field.key] = newValue;
          modifiedFields[`${field.key}_old`] = oldValue;
        }
      }

      if (isModified) {
        // Include all fields in the output
        changes.modified.push({
          ...item2,
          ...modifiedFields
        });
      }
    }
  }

  // Find deleted items
  for (const [id, item1] of json1Map.entries()) {
    if (!json2Map.has(id)) {
      // Item is deleted
      changes.deleted.push(item1);
    }
  }

  return changes;
};

let recorddata;
let changecount = 0;
let subject;

const App = (pagedata) => {
  const [selectedRecord, setSelectedRecord] = useState(null);
  const [loading, setLoading] = useState(true); // 加载状态
  const [listData, setListData] = useState([]);
  const [changes, setChanges] = useState([]);
  const [changesdetail, setChangesdetail] = useState([]);
  const [modalContent, setModalContent] = useState(null);
  const [modalVisible, setModalVisible] = useState(0);


  let dataid = pagedata?.data?.EntityId[0];
  let Entityname = pagedata?.data?.Entity;


  const fetchData = useCallback(async () => {
    setLoading(true); // 开始加载
    try {

      recorddata = await getCrmRecordById(Entityname, dataid);
      // console.log("recorddata", recorddata);
      subject = recorddata?.Name;


      // 请求列表数据
      const sql = `select Name,Owner.first_name as Ownername,id,OrderNo,ChangeContent,ChangeReason,ChangeDate,ChangeTimes,ModuleName from ChangeAll where id is not null and (Name like '%${subject}%' and ModuleName = '生产发货通知单') order by id desc`;
      const listresult = await getCrmRecordFromSql(sql);

      if (listresult && listresult.length > 0) {
        setListData(listresult);
        changecount = listresult.length;
        setSelectedRecord(listresult[0]);
        //拿到旧数据的json文件
        let selectdataid = listresult[0].id;
        let text = await getFileContentAsString(selectdataid);
        let olddata = JSON.parse(text);
        console.log("olddata", olddata);

        const changes = compareJson(olddata, recorddata, fieldsToCompare);
        const changesdetail = compareChildTables(olddata?.LinkingModule8, recorddata?.LinkingModule8, childFieldsToCompare);
        // console.log("changesdetail", changesdetail);

        const processedData = [
          ...changesdetail.added.map(item => ({ ...item, status: '新增', key: item.id })),
          ...changesdetail.modified.map(item => ({ ...item, status: '修改', key: item.id })),
          ...changesdetail.deleted.map(item => ({ ...item, status: '删除', key: item.id }))
        ];
        setChanges(changes);
        setChangesdetail(processedData);
        // console.log("changes", changes);

      } else {
        message.success('该数据无变更记录');
        setTimeout(() => {
          window.ZOHO.CRM.UI.Popup.close(); // 关闭弹出窗口
        }, 500);
      }
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      setLoading(false); // 完成加载
    }

  }, [dataid, Entityname]);

  useEffect(() => {
    const initialize = async () => {
      await window.zohoReadyPromise;
      console.log("ZOHO is ready", window.ZOHO);
      await window.ZOHO.CRM.UI.Resize({ height: "2000", width: "2000" });
      fetchData();
    };
    initialize();
  }, [fetchData]);



  const columns = [
    {
      title: '变更单号',
      dataIndex: 'Name',
      key: 'Name',
      width: 150,
    },
    {
      title: '单据号',
      dataIndex: 'OrderNo',
      key: 'OrderNo',
      width: 150,
    },
    {
      title: '操作员',
      dataIndex: 'Ownername',
      key: 'Ownername',
      width: 100,
    },
    {
      title: '变更日期',
      dataIndex: 'ChangeDate',
      key: 'ChangeDate',
      width: 110,
    },
    {
      title: '变更次数',
      dataIndex: 'ChangeTimes',
      key: 'ChangeTimes',
      width: 80,
    },
    {
      title: '变更原因',
      dataIndex: 'ChangeReason',
      key: 'ChangeReason',
      width: 200,
    },
    {
      title: '变更内容',
      dataIndex: 'ChangeContent',
      key: 'ChangeContent',
      width: 200,
    },
  ];

  const handleRowClick = async (record) => {
    try {
      setLoading(true); // 开始加载
      setSelectedRecord(record);
      //获取选中数据的json
      let selectdataid = record.id;
      let selectdatatxt = await getFileContentAsString(selectdataid);
      if (selectdatatxt) {
        let olddata = JSON.parse(selectdatatxt);
        let changeTimes = record?.ChangeTimes;
        let lastrecorddata = recorddata;

        if (changeTimes < changecount) {
          let lasttimes = changeTimes + 1;
          const sql = `select Name,Owner.first_name as Ownername,id,OrderNo,ChangeContent,ChangeReason,ChangeDate,ChangeTimes,ModuleName from ChangeAll where (ChangeTimes = ${lasttimes} and (Name like '%${subject}%' and ModuleName = '生产发货通知单'))`;
          // console.log("sql", sql);
          const listresult = await getCrmRecordFromSql(sql);
          // console.log("listresult", listresult);
          if (listresult && listresult.length > 0) {
            
            let lastrecorddtxt = await getFileContentAsString(listresult[0]?.id);
            if(lastrecorddtxt){
              lastrecorddata = JSON.parse(lastrecorddtxt);
            }
          }
        }

        const changes = compareJson(olddata, lastrecorddata, fieldsToCompare);

        const changesdetail = compareChildTables(olddata?.LinkingModule8, lastrecorddata?.LinkingModule8, childFieldsToCompare);
        const processedData = [
          ...changesdetail.added.map(item => ({ ...item, status: '新增', key: item.id })),
          ...changesdetail.modified.map(item => ({ ...item, status: '修改', key: item.id })),
          ...changesdetail.deleted.map(item => ({ ...item, status: '删除', key: item.id }))
        ];
        setChanges(changes);
        setChangesdetail(processedData);
        setChanges(changes);




      }
    } catch (error) {
      console.error('Error fetching data:', error);
    } finally {
      setLoading(false); // 结束加载
    }
  };

  const detailcolumns = [
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 70,
      ellipsis: true,
      fixed: 'left',
      render: text => (
        <span
          style={{
            color: text === '删除' ? 'red' :
              text === '修改' ? 'orange' :
                text === '新增' ? 'blue' :
                  'black'
          }}
        >
          {text}
        </span>
      ),
    },
    {
      title: '客户订单号',
      dataIndex: 'AccountOrderNo',
      key: 'AccountOrderNo',
      width: 100,
      ellipsis: true,
      fixed: 'left',
    },
    {
      title: '商品编码',
      dataIndex: ['Product', 'name'],
      key: 'Product.name',
      width: 100,
      ellipsis: true,
      fixed: 'left',
    },
    {
      title: '客户货号',
      dataIndex: 'AccountprtNo',
      key: 'AccountprtNo',
      width: 100,
      ellipsis: true,
    },
    {
      title: '内部货号',
      dataIndex: 'internalcode',
      key: 'internalcode',
      width: 100,
      ellipsis: true,
    },
    {
      title: '中文品名',
      dataIndex: 'Productname',
      key: 'Productname',
      width: 100,
      ellipsis: true,
    },
    {
      title: '中文规格',
      dataIndex: 'Chinesespecification',
      key: 'Chinesespecification',
      width: 100,
      ellipsis: true,
    },
    {
      title: '中文生产要求(材质)',
      dataIndex: 'Chptrequirements_material',
      key: 'Chptrequirements_material',
      width: 100,
      ellipsis: true,
    },
    {
      title: '中文成份',
      dataIndex: 'Chineseingredients',
      key: 'Chineseingredients',
      width: 100,
      ellipsis: true,
    },
    {
      title: '品牌',
      dataIndex: 'Brand',
      key: 'Brand',
      width: 100,
      ellipsis: true,
    },
    {
      title: '英文货名',
      dataIndex: 'Englishname',
      key: 'Englishname',
      width: 100,
      ellipsis: true,
    },
    {
      title: '英文规格',
      dataIndex: 'Specification',
      key: 'Specification',
      width: 100,
      ellipsis: true,
    },
    {
      title: '数量',
      dataIndex: 'Quantity',
      key: 'Quantity',
      width: 100,
      ellipsis: true,
    },
    {
      title: '单价',
      dataIndex: 'Purchaseunitprice',
      key: 'Purchaseunitprice',
      width: 100,
      ellipsis: true,
    },
    {
      title: '金额(USD)',
      dataIndex: 'PurchaseAmount',
      key: 'PurchaseAmount',
      width: 100,
      ellipsis: true,
    },
    {
      title: '单位',
      dataIndex: 'Unit',
      key: 'Unit',
      width: 100,
      ellipsis: true,
    },
    {
      title: '入数',
      dataIndex: 'Nuofboxesinpg',
      key: 'Nuofboxesinpg',
      width: 100,
      ellipsis: true,
    },
    {
      title: '内盒数',
      dataIndex: 'Nuofboxeinnerbox',
      key: 'Nuofboxeinnerbox',
      width: 100,
      ellipsis: true,
    },
    {
      title: '每箱装量',
      dataIndex: 'Packagingquantityperpg',
      key: 'Packagingquantityperpg',
      width: 100,
      ellipsis: true,
    },
    {
      title: '包装单位',
      dataIndex: 'Packaginunit',
      key: 'Packaginunit',
      width: 100,
      ellipsis: true,
    },
    {
      title: '长(CM)',
      dataIndex: 'Lengthofouterbox',
      key: 'Lengthofouterbox',
      width: 100,
      ellipsis: true,
    },
    {
      title: '宽(CM)',
      dataIndex: 'Cartonwidth',
      key: 'Cartonwidth',
      width: 100,
      ellipsis: true,
    },
    {
      title: '高(CM)',
      dataIndex: 'Heightofouterbox',
      key: 'Heightofouterbox',
      width: 100,
      ellipsis: true,
    },
    {
      title: '体积',
      dataIndex: 'Volume',
      key: 'Volume',
      width: 100,
      ellipsis: true,
    },
    {
      title: '外箱净重(KG)',
      dataIndex: 'Netweight',
      key: 'Netweight',
      width: 100,
      ellipsis: true,
    },
    {
      title: '外箱毛重(KG)',
      dataIndex: 'Grossweight',
      key: 'Grossweight',
      width: 100,
      ellipsis: true,
    },
    {
      title: '箱数',
      dataIndex: 'PackQty',
      key: 'PackQty',
      width: 100,
      ellipsis: true,
    },

    {
      title: '唛头',
      dataIndex: 'ShippingMark',
      key: 'ShippingMark',
      width: 100,
      ellipsis: true,
    },

    {
      title: '总计',
      dataIndex: 'Net_Total',
      key: 'Net_Total',
      width: 100,
      ellipsis: true,
    },
    {
      title: '箱数',
      dataIndex: 'NumberofCartons',
      key: 'NumberofCartons',
      width: 100,
      ellipsis: true,
    },
    {
      title: '类别',
      dataIndex: 'Category',
      key: 'Category',
      width: 100,
      ellipsis: true,
    },
    {
      title: '总毛重',
      dataIndex: 'Nuofboxesinpg',
      key: 'Nuofboxesinpg',
      width: 100,
      ellipsis: true,
    },
    {
      title: '总净重',
      dataIndex: 'TotalNetweight',
      key: 'TotalNetweight',
      width: 100,
      ellipsis: true,
    },
    {
      title: '总体积',
      dataIndex: 'TotalVolume',
      key: 'TotalVolume',
      width: 100,
      ellipsis: true,
    }
  ];
  const handleDetailRowClick = (record) => {
    if (record.status === '修改') {
      // 创建一个字段名称映射表
      const fieldNameMap = detailcolumns.reduce((map, column) => {
        map[column.dataIndex] = column.title;
        return map;
      }, {});

      // 过滤出需要修改的字段并生成修改内容
      const modifiedFields = Object.keys(record).filter(key => key.endsWith('_old')).reduce((acc, key) => {
        const originalField = key.replace('_old', '');
        acc[originalField] = {
          field: fieldNameMap[originalField] || originalField, // 获取字段名称
          originalValue: record[key],
          newValue: record[originalField]
        };
        return acc;
      }, {});

      setModalContent(modifiedFields);
      setModalVisible(true);
    }
  };
  const ModalContent = ({ content }) => {
    return (
      <div>
        {Object.keys(content).length > 0 ? (
          <Table
            dataSource={Object.values(content)}
            columns={[
              { title: '字段名', dataIndex: 'field', key: 'field' },
              { title: '原值', dataIndex: 'originalValue', key: 'originalValue' },
              { title: '新值', dataIndex: 'newValue', key: 'newValue' },
            ]}
            pagination={false}
            size="small"
          />
        ) : (
          <div>没有修改内容</div>
        )}
      </div>
    );
  };


  return (
    <>
      <Spin spinning={loading} tip="加载中..." style={{ minHeight: '100vh', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
        <Layout style={{ height: '100vh' }}>
          <Sider width={400} style={{ background: '#fff', height: '100vh', display: 'flex', flexDirection: 'column' }}>
            <div style={{ flex: 1, overflow: 'auto' }}>
              <Table
                dataSource={listData.map((item) => ({ ...item, key: item.id }))}
                columns={columns}
                pagination={false}
                onRow={(record) => ({
                  onClick: () => handleRowClick(record),
                })}
                rowClassName={(record) =>
                  record.key === selectedRecord?.key ? 'selected-row' : ''
                }
                size="Large"
                tableLayout="fixed" // 确保表格列宽固定
              />
            </div>
          </Sider>
          <Layout>
            <Content style={{ margin: '2px 2px 2px 2px', overflow: 'initial' }}>
              <div style={{ background: '#fff', padding: '5px', marginBottom: '8px' }}>
                <h3>变更详情</h3>
                {selectedRecord ? (
                  <>
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '16px', marginBottom: '8px' }}>
                      <div>变更单号: {selectedRecord.Name}</div>
                      <div>单据号: {selectedRecord.OrderNo}</div>
                      <div>操作员: {selectedRecord.Ownername}</div>
                      <div>变更日期: {selectedRecord.ChangeDate}</div>
                    </div>
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '16px' }}>
                      <div>变更次数: {selectedRecord.ChangeTimes}</div>
                      <div style={{ minWidth: '200px', wordWrap: 'break-word', overflowWrap: 'break-word' }}>
                        变更原因: {selectedRecord.ChangeReason}
                      </div>
                      <div style={{ minWidth: '200px', wordWrap: 'break-word', overflowWrap: 'break-word' }}>
                        变更内容: {selectedRecord.ChangeContent}
                      </div>
                      {/* <div>模块名称: {selectedRecord.ModuleName}</div> */}
                    </div>
                  </>
                ) : (
                  <div>请选择一行查看详情</div>
                )}
              </div>
              <div style={{ background: '#fff', padding: '0px', marginBottom: '5px' }}>
                <h3>主表变更情况</h3>
                <Table
                  dataSource={changes}
                  columns={[
                    { title: '字段名', dataIndex: 'field', key: 'field' },
                    { title: '原值', dataIndex: 'originalValue', key: 'originalValue' },
                    { title: '新值', dataIndex: 'newValue', key: 'newValue' },
                  ]}
                  pagination={false}
                  size="small"
                />
              </div>
              <div style={{ background: '#fff', padding: '0px', marginBottom: '5px' }}>
                <h3>子表变更情况</h3>
                <Table
                  dataSource={changesdetail}
                  columns={detailcolumns}
                  rowKey="key"
                  size="small"
                  tableLayout="fixed" // 确保表格列宽固定
                  scroll={{ x: 'max-content' }} // 水平滚动
                  onRow={(record) => ({
                    onClick: () => handleDetailRowClick(record),
                  })}
                />
              </div>
            </Content>
          </Layout>
        </Layout>
      </Spin>
      <Modal
        title="修改详情"
        visible={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
      >
        <ModalContent content={modalContent} />
      </Modal>
    </>
  );
};

export default App;
